<template>
  <el-cascader
    v-model="cascaderValue"
    :options="data"
    :props="{
      children: 'c',
      label: 'n',
      value: 'n'
    }"
    clearable
    @change="onCascaderValueChange"
    v-bind="$attrs"
  >
  </el-cascader>
</template>


<script>
import data from './data.json';

export default {
  name: 'AreaSelect',
  inheritAttrs: false,
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: [Object, String]
  },
  data() {
    return {
      cascaderValue: null,
      data: data
    };
  },
  watch: {
    value(val) {
      if (typeof val == 'string') {
        this.cascaderValue = val.split(',');
      } else {
        this.cascaderValue = val ? Object.values(val).filter(Boolean) : null;
      }
    }
  },
  mounted() {
    this.value && this.setValue(this.value);
  },
  methods: {
    onCascaderValueChange(value) {
      let ret = {
        prov: value[0]
      };
      if (value.length == 2) {
        ret.city = '';
        ret.dist = value[1];
      } else if (value.length == 3) {
        ret.city = value[1];
        ret.dist = value[2];
      } else {
        ret = null;
      }

      this.$emit('change', ret);
    },
    setValue(value) {
      this.cascaderValue = Object.values(value).filter(Boolean);
      this.onCascaderValueChange(this.cascaderValue);
    },
    clear() {
      this.cascaderValue = [];
      this.onCascaderValueChange(this.cascaderValue);
    }
  },
}
</script>